package craky.keeper.util;

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.PropertyResourceBundle;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.animation.LinearInterpolator;
import craky.keeper.bean.Category;
import craky.keeper.bean.ResultSet;
import craky.keeper.bean.User;
import craky.keeper.remote.RemoteInterface;

public class KeeperUtil
{
    public static final String TYPE_EXTRA = "\u989D\u5916";

    public static final String KEY_KEEPER_DATA = "Keeper_Data";

    public static final String KEY_IS_PAY = "Is_Pay";

    public static final String KEY_ACTION = "Action";

    public static final String ACTION_DELETE = "Delete";

    public static final String ACTION_ADD = "Add";

    public static final String ACTION_MODIFY = "Modify";

    public static final String ACTION_SHOW_DETAIL = "Show_Detail";

    public static final int REQUEST_CODE_ADD = 1;

    public static final int REQUEST_CODE_MODIFY = 2;

    public static final int RESULT_CODE_OK = 100;

    public static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    public static final LinearInterpolator LINEAR_INTERPOLATOR = new LinearInterpolator();

    private static final Map<String, Category> payCategoryMap = new LinkedHashMap<String, Category>();

    private static final Map<String, Category> incomeCategoryMap = new LinkedHashMap<String, Category>();

    public static float density;

    public static User currentUser;

    public static String currentIp;

    public static RemoteInterface remote;

    public static float getDisplayDensity(Activity activity)
    {
        if(density == 0)
        {
            DisplayMetrics metric = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
            density = metric.density;
        }

        return density;
    }

    public static int getActivityTop(Activity activity)
    {
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        return rect.top;
    }

    public static boolean hasExternalStorage()
    {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static String getLocalDatasParent()
    {
        String path = null;

        if(hasExternalStorage())
        {
            File externalStorage = Environment.getExternalStorageDirectory();
            String parentPath = externalStorage.getAbsolutePath() + "/Keeper";
            File dataRoot = new File(parentPath + "/data");

            if(dataRoot.exists() && dataRoot.isDirectory())
            {
                path = parentPath;
            }
        }

        return path;
    }

    public static int getCustomPort()
    {
        int port = 30330;
        String configFilePath = null;

        if(hasExternalStorage())
        {
            File externalStorage = Environment.getExternalStorageDirectory();
            String path = externalStorage.getAbsolutePath() + "/Keeper/config.properties";
            File configFile = new File(path);

            if(configFile.exists())
            {
                configFilePath = path;
            }
        }

        if(configFilePath != null)
        {
            FileInputStream inputStream = null;

            try
            {
                inputStream = new FileInputStream(configFilePath);
                PropertyResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
                port = Integer.parseInt(resourceBundle.getString("Server_Port"));
            }
            catch(Exception e)
            {
                port = 30330;
            }
            finally
            {
                if(inputStream != null)
                {
                    try
                    {
                        inputStream.close();
                    }
                    catch(Exception e)
                    {}
                }
            }
        }

        return port;
    }

    public static void cacheCategories(ResultSet resultSet)
    {
        List<Category> categoryList = resultSet.getPayCategoryList();

        if(categoryList != null)
        {
            payCategoryMap.clear();

            for(Category category: categoryList)
            {
                payCategoryMap.put(category.getName(), category);
            }
        }

        categoryList = resultSet.getIncomeCategoryList();

        if(categoryList != null && currentUser.getPurview() < User.VISITOR)
        {
            incomeCategoryMap.clear();

            for(Category category: categoryList)
            {
                incomeCategoryMap.put(category.getName(), category);
            }
        }
    }

    public static Category getCategory(String name, boolean isPay)
    {
        return isPay? payCategoryMap.get(name): incomeCategoryMap.get(name);
    }

    public static void removeCategory(String name, boolean isPay)
    {
        Map<String, Category> categoryMap = isPay? payCategoryMap: incomeCategoryMap;
        categoryMap.remove(name);
    }

    public static String[] getCategoryNames(boolean isPay)
    {
        Collection<Category> categoryList = isPay? payCategoryMap.values(): incomeCategoryMap.values();
        String[] names = new String[categoryList.size()];
        int index = 0;

        for(Category category: categoryList)
        {
            names[index++] = category.getName();
        }

        return names;
    }

    public static String[] getDateArrays(int size)
    {
        String[] dateArrays = new String[size];
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -size + 1);

        for(int index = 0; index < size; index++)
        {
            dateArrays[index] = DATE_FORMAT.format(calendar.getTime());
            calendar.add(Calendar.DAY_OF_YEAR, 1);
        }

        return dateArrays;
    }
}